package lesson04.作业.作业01;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 实现一个容器，提供两个方法，add，size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 * CountDownLatch 如果只使用一个，且没有加sleep则输出不准确
 */
public class ThreadDemo2 {

    public static void main(String[] args) {

        TList container = new TList();
        //调用countDown方法后-1，门就开了
        CountDownLatch latch = new CountDownLatch(1);
        new Thread(()->{
            System.out.println("t2启动");
            if(container.size() != 5){
                try {
                    latch.await();
                    //也可以指定等待时间
                    //latch.await(5,TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t2结束");
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            System.out.println("t1启动");
            for(int i =0;i < 10;i++){
                container.add(new Object());
                System.out.println("add"+i);
                if(container.size() == 5){
                    //打开门闩，让t2得以执行
                    latch.countDown();
                }
               /* try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
            }
        },"t1").start();
    }
}
